<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards no-wrap-row fixed-width-row">
      <div v-for="stat in stats" :key="stat.title" class="stat-col fixed-stat-col">
        <el-card shadow="never" class="stat-card compact-stat-card">
          <div>
            <div class="stat-card-title">{{ stat.title }}</div>
            <div class="stat-card-num" :style="{ color: stat.color }">{{ stat.value }}</div>
          </div>
          <i :class="['stat-icon', stat.icon]" :style="{ color: stat.color }"></i>
        </el-card>
      </div>
    </el-row>
    <el-row :gutter="20">
      <!-- 设备类型菜单 -->
      <el-col :xs="24" :sm="24" :md="4">
        <el-card shadow="never">
          <div
            style="font-weight:bold; margin-bottom:10px; display: flex; align-items: center; justify-content: space-between;">
            <span>设备类型</span>
            <i class="el-icon-plus type-add-icon" @click="showAddTypeDialog = true" style="cursor:pointer;"></i>
          </div>
          <el-menu :default-active="activeType" @select="handleTypeSelect">
            <el-menu-item v-for="type in deviceTypes" :key="type.value" :index="type.value"
              style="display: flex; align-items: center; justify-content: space-between;">
              <div style="display: flex; align-items: center;">
                <i :class="type.icon"></i>
                <span slot="title" style="margin-left: 8px;">{{ type.label }}</span>
              </div>
              <i class="type-delete-icon el-icon-delete" style="color: #F56C6C; margin-left: auto; cursor: pointer;"
                @click.stop="handleDeleteType(type)"></i>
            </el-menu-item>
            <!-- 空状态显示 -->
            <div v-if="deviceTypes.length === 0" style="padding: 20px; text-align: center; color: #909399;">
              <i class="el-icon-folder-opened" style="font-size: 24px; margin-bottom: 8px;"></i>
              <div>暂无设备类型</div>
              <div style="font-size: 12px; margin-top: 4px;">点击上方"+"添加设备类型</div>
            </div>
          </el-menu>
        </el-card>
      </el-col>
      <!-- 设备详情与时间轴和原有内容 -->
      <el-col :xs="24" :sm="24" :md="20">
        <el-card shadow="never" class="main-card">
          <!-- 原有表单、表格等内容 -->
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="90px" @submit.native.prevent>
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名称" clearable
                @keyup.enter.native.prevent="handleQuery" />
            </el-form-item>
            <el-form-item label="设备编号" prop="equipmentCode">
              <el-input v-model="queryParams.equipmentCode" placeholder="请输入设备编号" clearable
                @keyup.enter.native.prevent="handleQuery" />
            </el-form-item>
            <el-form-item label="型号" prop="model">
              <el-input v-model="queryParams.model" placeholder="请输入型号" clearable
                @keyup.enter.native.prevent="handleQuery" />
            </el-form-item>
            <el-form-item label="出厂编号" prop="serialNumber">
              <el-input v-model="queryParams.serialNumber" placeholder="请输入出厂编号" clearable
                @keyup.enter.native.prevent="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="数量" prop="quantity">
              <el-input v-model="queryParams.quantity" placeholder="请输入数量" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-input v-model="queryParams.unit" placeholder="请输入单位" clearable @keyup.enter.native="handleQuery" />
            </el-form-item> -->
            <el-form-item label="设备所在地" prop="location">
              <el-input v-model="queryParams.location" placeholder="请输入设备所在地" clearable
                @keyup.enter.native.prevent="handleQuery" />
            </el-form-item>
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable filterable>
                <el-option v-for="dict in dict.type.equipment_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-left: 50px;">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['equipment:main:add']">新增</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['equipment:main:edit']">修改</el-button>
            </el-col> -->
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['equipment:main:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['equipment:main:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <div class="table-responsive">
            <el-table v-loading="loading" :data="mainList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <!-- <el-table-column label="主键" align="center" prop="id" /> -->
              <el-table-column label="设备名称" align="center" prop="equipmentName" />
              <el-table-column label="设备编号" align="center" prop="equipmentCode" />
              <el-table-column label="型号" align="center" prop="model" />
              <el-table-column label="出厂编号" align="center" prop="serialNumber" />
              <el-table-column label="数量" align="center" prop="quantity" />
              <el-table-column label="单位" align="center" prop="unit" />
              <el-table-column label="设备所在地" align="center" prop="location" />
              <el-table-column label="设备状态" align="center" prop="status">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.equipment_status" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" width="120">
                <template slot-scope="scope">
                  <span class="ellipsis-cell" :title="scope.row.remark">{{ scope.row.remark }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="160" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                    v-hasPermi="['equipment:main:remove']">删除</el-button>
                  <el-dropdown trigger="click">
                    <el-button size="mini" type="text" icon="el-icon-more">更多</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="handleUpdate(scope.row)" v-hasPermi="['equipment:main:edit']">
                        <i class="el-icon-edit"></i> 修改
                      </el-dropdown-item>
                      <el-dropdown-item @click.native="handleTransfer(scope.row)"
                        v-hasPermi="['equipment:main:transferRecords']">
                        <i class="el-icon-s-promotion"></i> 调拨
                      </el-dropdown-item>
                      <el-dropdown-item @click.native="handleRepair(scope.row)"
                        v-hasPermi="['equipment:main:repairHistory']">
                        <i class="el-icon-s-tools"></i> 维修
                      </el-dropdown-item>
                      <el-dropdown-item @click.native="handleShowLogs(scope.row)"
                        v-hasPermi="['equipment:main:deviceLog']">
                        <i class="el-icon-document"></i> 设备记录
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>



    <!-- 添加或修改设备主对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="dialogWidth" append-to-body>
      <el-form ref="forms" :model="forms" :rules="rules" label-width="100px">
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model="forms.equipmentName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentCode">
          <el-input v-model="forms.equipmentCode" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="forms.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="出厂编号" prop="serialNumber">
          <el-input v-model="forms.serialNumber" placeholder="请输入出厂编号" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="forms.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="forms.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="设备所在地" prop="location">
          <el-input v-model="forms.location" placeholder="请输入设备所在地" />
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-radio-group v-model="forms.status">
            <el-radio v-for="dict in dict.type.equipment_status" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="forms.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加设备类型对话框 -->
    <el-dialog title="添加设备类型" :visible.sync="showAddTypeDialog" :width="dialogWidth" append-to-body
      @close="addTypeForm.typeName = ''">
      <el-form :model="addTypeForm" @submit.native.prevent>
        <el-form-item label="类型名称" label-width="80px">
          <el-input v-model="addTypeForm.typeName" placeholder="请输入类型名称" @keyup.enter.native.prevent />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddTypeDialog = false">取 消</el-button>
        <el-button type="primary" :loading="addTypeLoading" @click="handleAddType">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 设备调拨对话框 -->
    <el-dialog title="设备调拨" :visible.sync="transferDialogVisible" :width="dialogWidth" append-to-body>
      <el-form :model="transferForm" ref="transferFormRef" label-width="100px" @submit.native.prevent>
        <el-form-item label="设备名称">
          <el-input v-model="transferForm.equipmentName" disabled />
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input v-model="transferForm.equipmentCode" disabled />
        </el-form-item>
        <el-form-item label="设备型号">
          <el-input v-model="transferForm.model" disabled />
        </el-form-item>
        <el-form-item label="调出地点" prop="transferOutLocation"
          :rules="[{ required: true, message: '请输入调出位置', trigger: 'blur' }]">
          <el-input v-model="transferForm.transferOutLocation" placeholder="请输入调出位置" @keyup.enter.native.prevent />
        </el-form-item>
        <el-form-item label="调入地点" prop="transferInLocation"
          :rules="[{ required: true, message: '请输入调入位置', trigger: 'blur' }]">
          <el-input v-model="transferForm.transferInLocation" placeholder="请输入调入位置" @keyup.enter.native.prevent />
        </el-form-item>
        <el-form-item label="调拨原因" prop="remark">
          <el-input v-model="transferForm.remark" type="textarea" placeholder="请输入内容" @keyup.enter.native.prevent />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="transferDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTransfer">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加维修记录对话框 -->
    <el-dialog title="添加维修记录" :visible.sync="repairDialogVisible" :width="dialogWidth" append-to-body>
      <el-form :model="repairForm" ref="repairFormRef" label-width="140px" @submit.native.prevent>
        <el-form-item label="设备名称">
          <el-input v-model="repairForm.equipmentName" disabled />
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input v-model="repairForm.equipmentCode" disabled />
        </el-form-item>
        <el-form-item label="设备型号">
          <el-input v-model="repairForm.model" disabled />
        </el-form-item>
        <el-form-item label="状态描述" prop="statusDescription"
          :rules="[{ required: true, message: '请输入状态描述', trigger: 'blur' }]">
          <el-input v-model="repairForm.statusDescription" type="textarea" placeholder="请输入内容"
            @keyup.enter.native.prevent />
        </el-form-item>
        <!-- <el-form-item label="状态描述处理情况" prop="statusDescriptionAction"
          :rules="[{ required: true, message: '请选择状态', trigger: 'blur' }]">
          <el-radio-group v-model="repairForm.statusDescriptionAction">
            <el-radio v-for="dict in dict.type.status_description_handing_situation" :key="dict.value"
              :label="parseInt(dict.value)">{{
                dict.label
              }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="设备维修问题点" prop="repairIssues"
          :rules="[{ required: true, message: '请输入设备维修问题点', trigger: 'blur' }]">
          <el-input v-model="repairForm.repairIssues" type="textarea" placeholder="请输入内容" @keyup.enter.native.prevent />
        </el-form-item>
        <el-form-item label="维修记录" prop="repairRecords"
          :rules="[{ required: true, message: '请输入维修记录', trigger: 'blur' }]">
          <el-input v-model="repairForm.repairRecords" type="textarea" placeholder="请输入内容"
            @keyup.enter.native.prevent />
        </el-form-item>
        <el-form-item label="预计完成时间" prop="expectedCompletionTime"
          :rules="[{ required: true, message: '请选择预计完成时间', trigger: 'change' }]">
          <el-date-picker clearable v-model="repairForm.expectedCompletionTime" type="date"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择预计完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态描述处理情况" prop="completionStatus"
          :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
          <el-radio-group v-model="repairForm.completionStatus">
            <el-radio v-for="dict in dict.type.performance" :key="dict.value" :label="parseInt(dict.value)">{{
              dict.label
            }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="是否信息变更" prop="isInfoChange"
          :rules="[{ required: true, message: '请选择是否是信息变更', trigger: 'change' }]">
          <el-radio-group v-model="repairForm.isInfoChange">
            <el-radio :label="'1'">是</el-radio>
            <el-radio :label="'0'">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="repairForm.remark" type="textarea" placeholder="请输入内容" @keyup.enter.native.prevent />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="repairDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRepair">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 维修记录日志弹框（新） -->
    <el-dialog title="维修记录详情" :visible.sync="logDialogVisible" :width="dialogWidth" append-to-body>
      <div class="device-info">
        <div class="info-item">
          <div class="label">设备名称</div>
          <div class="value">{{ logDetailInfo.equipmentName }}</div>
        </div>
        <div class="info-item">
          <div class="label">型号</div>
          <div class="value">{{ logDetailInfo.model }}</div>
        </div>
        <div class="info-item">
          <div class="label">设备编号</div>
          <div class="value">{{ logDetailInfo.equipmentCode }}</div>
        </div>
        <div class="info-item">
          <div class="label">出厂编号</div>
          <div class="value">{{ logDetailInfo.serialNumber }}</div>
        </div>
        <div class="info-item">
          <div class="label">数量</div>
          <div class="value">{{ logDetailInfo.quantity }}</div>
        </div>
        <div class="info-item">
          <div class="label">单位</div>
          <div class="value">{{ logDetailInfo.unit }}</div>
        </div>
        <div class="info-item">
          <div class="label">设备所在</div>
          <div class="value"><i class="el-icon-location"></i>{{ logDetailInfo.location }}</div>
        </div>
        <div class="info-item">
          <div class="label">设备状态</div>
          <div class="value">
            <!-- <el-tag :type="statusTagType(logDetailInfo.status)" effect="light" round>{{
            logDetailInfo.status }}</el-tag> -->
            <dict-tag :options="dict.type.equipment_status" :value="logDetailInfo.status" />
          </div>
        </div>
      </div>
      <el-timeline>
        <el-timeline-item v-for="(item, idx) in logTimeline" :key="item.date + '-' + idx" :timestamp="item.date"
          :color="getTimelineColor(item.type)" placement="top">
          <el-card class="timeline-card" :style="{ borderLeft: `4px solid ${getTimelineColor(item.type)}` }"
            shadow="never">
            <div style="display: flex; align-items: center; width: 100%;">
              <div style="flex: 1; min-width: 0;">
                <div class="timeline-title">{{ item.title }}</div>
                <div v-if="item.type === 'maintenance'" class="maintenance-desc">
                  <span class="detail-label">维修问题点：</span>{{ item.repairIssues }} <br />
                  <span class="detail-label">状态描述：</span>{{ item.desc }}<br />
                  <span class="detail-label">维修记录：</span>{{ item.repairRecords }}
                </div>
                <div v-else-if="item.type === 'transfer'" class="transfer-desc">
                  <div>调出地点: {{ item.from }}</div>
                  <div>调入地点: {{ item.to }}</div>
                </div>
                <div v-else class="default-desc">
                  {{ item.desc }}
                </div>
              </div>
              <div style="display: flex; justify-content: flex-end; flex-shrink: 0; margin-left: 20px;">

                <el-button v-if="item.type === 'maintenance'" size="small" type="danger">设备维修</el-button>
                <el-button v-else-if="item.type === 'transfer'" size="small" type="primary">设备调转</el-button>
                <el-button v-if="item.type == 'maintenance' && item.isInfoChange == 1" size="small"
                  type="warning">消息变更</el-button>
                <el-button v-if="item.type == 'maintenance' && item.completionStatus == 1" size="small"
                  type="success">维修完成</el-button>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <div slot="footer" class="dialog-footer">
        <el-button @click="logDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 设备详情对话框 -->
    <el-dialog :visible.sync="detailDialogVisible" width="900px" :show-close="true" append-to-body
      class="daily-detail-dialog">
      <div class="daily-detail-title">设备详情</div>
      <div class="daily-section-title">基本信息</div>
      <div class="daily-row-flex">
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">设备名称</th>
              <td class="value">{{ detailForm.equipmentName }}</td>
            </tr>
            <tr>
              <th class="left-align">设备编号</th>
              <td class="value">{{ detailForm.equipmentCode }}</td>
            </tr>
            <tr>
              <th class="left-align">型号</th>
              <td class="value">{{ detailForm.model }}</td>
            </tr>
            <tr>
              <th class="left-align">出厂编号</th>
              <td class="value">{{ detailForm.serialNumber }}</td>
            </tr>
          </table>
        </div>
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">数量</th>
              <td class="value">{{ detailForm.quantity }}</td>
            </tr>
            <tr>
              <th class="left-align">单位</th>
              <td class="value">{{ detailForm.unit }}</td>
            </tr>
            <tr>
              <th class="left-align">设备所在地</th>
              <td class="value">{{ detailForm.location }}</td>
            </tr>
            <tr>
              <th class="left-align">设备状态</th>
              <td class="value">
                <dict-tag :options="dict.type.equipment_status" :value="detailForm.status" />
              </td>
            </tr>
          </table>
        </div>
      </div>
      <div class="daily-section-title">备注</div>
      <table class="daily-detail-table">
        <tr>
          <th class="center-bg">备注</th>
          <td class="value">{{ detailForm.remark }}</td>
        </tr>
      </table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false" type="primary" plain>关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listMain, getMain, delMain, addMain, updateMain, equipmentCount } from "@/api/equipment/main";
import { listType, getType, delType, addType, updateType } from "@/api/equipment/type";
import { listTransferRecords, getTransferRecords, delTransferRecords, addTransferRecords, updateTransferRecords } from "@/api/equipment/transferRecords";
import { addRepairHistory, newRepair, listRepairHistory, getRepairHistory, delRepairHistory, updateRepairHistory } from "@/api/equipment/repairHistory";

export default {
  name: "Main",
  dicts: ['equipment_status', 'performance', 'status_description_handing_situation'],
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备主表格数据
      mainList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      typeParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: null,
        remark: null
      },
      typeTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentName: null,
        equipmentCode: null,
        model: null,
        serialNumber: null,
        quantity: null,
        unit: null,
        location: null,
        status: null,
        remark: null,
        equipmentTypeId: null,
      },
      // 表单参数
      forms: {
        equipmentTypeId: '',
      },
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键不能为空", trigger: "blur" }
        ],
        equipmentName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        equipmentCode: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        model: [
          { required: true, message: "型号不能为空", trigger: "blur" }
        ],
        // serialNumber: [
        //   { required: true, message: "出厂编号不能为空", trigger: "blur" }
        // ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        location: [
          { required: true, message: "设备所在地不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "设备状态不能为空", trigger: "blur" }
        ],
        // remark: [
        //   { required: true, message: "备注不能为空", trigger: "blur" }
        // ]
      },
      // 统计卡片和设备类型菜单数据
      stats: [
        { title: '总设备数', value: 0, icon: 'el-icon-s-grid', color: '#333' },
        { title: '在线设备数', value: 0, icon: 'el-icon-circle-check', color: '#67C23A' },
        { title: '闲置设备数', value: 0, icon: 'el-icon-box', color: '#409EFF' },
        { title: '待检修设备数', value: 0, icon: 'el-icon-setting', color: '#E6A23C' },
        { title: '待报废设备数', value: 0, icon: 'el-icon-delete', color: '#ffc833' },
        { title: '已报废设备数', value: 0, icon: 'el-icon-delete', color: '#F56C6C' },
        { title: '维修中设备数', value: 0, icon: 'el-icon-set-up', color: '#ffa4a4' },
        // { title: '设备类型数', value: 0, icon: 'el-icon-menu', color: '#8e44ad', isTypeCount: true },
      ],
      deviceTypes: [
        // { label: '桩机', value: '1', icon: 'el-icon-place' },
        // { label: '地泵', value: '2', icon: 'el-icon-switch-button' },
        // { label: '发电机', value: '3', icon: 'el-icon-lightning' },
        // { label: '挖机', value: '4', icon: 'el-icon-truck' },
        // { label: '旋挖', value: '5', icon: 'el-icon-refresh' },
        // { label: '振动锤', value: '6', icon: 'el-icon-magic-stick' },
        // { label: '上动力头', value: '7', icon: 'el-icon-top' },
        // { label: '下动力头', value: '8', icon: 'el-icon-bottom' }
      ],
      activeType: '',
      showAddTypeDialog: false,
      addTypeForm: {
        typeName: ''
      },
      addTypeLoading: false,
      transferDialogVisible: false,
      transferForm: {
        equipmentId: '',
        equipmentName: '',
        fromLocation: '',
        toLocation: '',
        reason: ''
      },
      repairDialogVisible: false,
      repairForm: {
        equipmentId: '',
        equipmentName: '',
        equipmentCode: '',
        model: '',
        repairReason: '',
        repairResult: '',
        repairTime: '',
        // 其他需要的字段
        statusDescription: '',
        statusDescriptionAction: '',
        repairIssues: '',
        repairRecords: '',
        expectedCompletionTime: '',
        completionStatus: 2,
        isInfoChange: null,
        remark: '',
      },
      // 日志弹框相关
      logDialogVisible: false,
      logDetailInfo: {},
      logTimeline: [],
      dialogWidth: '680px',
      detailDialogVisible: false,
      detailForm: {
        equipmentName: '',
        equipmentCode: '',
        model: '',
        serialNumber: '',
        quantity: '',
        unit: '',
        location: '',
        status: '',
        remark: ''
      },
    };
  },
  created() {
    this.getCount()
    this.getTypeList();
    this.setDialogWidth();
    window.addEventListener('resize', this.setDialogWidth);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setDialogWidth);
  },
  methods: {
    setDialogWidth() {
      this.dialogWidth = window.innerWidth < 600 ? '95%' : '680px';
    },
    /** 查询设备类型列表 */
    getTypeList() {
      listType(this.typeParams).then(response => {
        this.deviceTypes = [];
        this.typeTotal = response.total;
        // 更新统计卡片的设备类型数
        if (this.stats && this.stats.length > 0) {
          const typeStat = this.stats.find(s => s.isTypeCount);
          if (typeStat) typeStat.value = this.typeTotal;
        }
        response.rows.forEach(item => {
          this.deviceTypes.push({
            label: item.typeName,
            value: String(item.id),
            icon: 'el-icon-mobile'
          });
        });

        // 检查设备类型列表是否为空
        if (this.deviceTypes.length > 0) {
          this.activeType = this.deviceTypes[0].value;
          this.queryParams.equipmentTypeId = this.deviceTypes[0].value;
        } else {
          // 如果没有设备类型，设置为null或空字符串
          this.activeType = '';
          this.queryParams.equipmentTypeId = null;
        }

        this.getList(); // 类型变动后自动刷新列表
      }).catch(error => {
        console.error('获取设备类型列表失败:', error);
        // 发生错误时也设置为空
        this.deviceTypes = [];
        this.activeType = '';
        this.queryParams.equipmentTypeId = null;
        this.getList(); // 仍然尝试获取设备列表
      });
    },
    /** 查询设备主列表 */
    getList() {
      console.log(2, this.queryParams, this.activeType);
      this.loading = true;
      listMain(this.queryParams).then(response => {
        this.mainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getCount()
    },

    /** 查询设备主列表 */
    getCount() {
      equipmentCount().then(response => {
        // console.log(11, response);
        this.stats[0].value = response.data[0]
        this.stats[1].value = response.data[1]
        this.stats[2].value = response.data[2]
        this.stats[3].value = response.data[3]
        this.stats[4].value = response.data[6]
        this.stats[5].value = response.data[4]
        this.stats[6].value = response.data[5]

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.forms = {
        id: null,
        equipmentName: null,
        equipmentCode: null,
        model: null,
        serialNumber: null,
        quantity: null,
        unit: null,
        location: null,
        status: "0",
        remark: null,
        equipmentTypeId: '',
      };
      this.resetForm("forms");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置类型为第一个（如有）
      if (this.deviceTypes && this.deviceTypes.length > 0) {
        this.activeType = this.deviceTypes[0].value;
        this.queryParams.equipmentTypeId = this.deviceTypes[0].value;
      } else {
        this.activeType = '';
        this.queryParams.equipmentTypeId = null;
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMain(id).then(response => {
        this.forms = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["forms"].validate(valid => {
        if (valid) {
          // 确保设备类型ID不为空，如果activeType为空则设置为null
          this.forms.equipmentTypeId = this.activeType || null;
          if (this.forms.id != null) {
            updateMain(this.forms).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMain(this.forms).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中数据？').then(function () {
        return delMain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('equipment/main/export', {
        ...this.queryParams
      }, `main_${new Date().getTime()}.xlsx`)
    },
    statusTagType(status) {
      const statusMap = {
        '在线': 'success',
        '闲置中': 'warning',
        '待检修': 'warning',
        '维修中': 'danger',
        '已报废': 'info'
      };
      return statusMap[status] || 'info';
    },
    getTimelineColor(type) {
      const colorMap = {
        'maintenance': '#f56c6c',
        'transfer': '#409eff',
      };
      return colorMap[type] || '#909399';
    },
    handleTypeSelect(val) {
      // console.log(3, val)
      this.activeType = String(val);
      this.queryParams.equipmentTypeId = String(val);
      this.forms.equipmentTypeId = String(val);
      this.getList();
    },
    handleDeleteType(type) {
      // 判断该类型下是否有设备数据
      const hasData = this.mainList && this.mainList.some(item => item.equipmentTypeId == type.value);
      if (hasData) {
        this.$message.warning('该类型下有设备，不能删除！');
        return;
      }
      this.$confirm(`是否确认删除设备类型"${type.label}"？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delType(type.value).then(() => {
          this.$message.success('删除成功');
          // 重新获取类型列表，自动处理 activeType 和 equipmentTypeId
          this.getTypeList();
        });
      }).catch(() => { });
    },
    handleAddType() {
      if (!this.addTypeForm.typeName.trim()) {
        this.$message.warning('请输入类型名称');
        return;
      }
      this.addTypeLoading = true;
      addType({ typeName: this.addTypeForm.typeName }).then(() => {
        this.$message.success('添加成功');
        this.showAddTypeDialog = false;
        this.addTypeForm.typeName = '';
        this.getTypeList();
      }).finally(() => {
        this.addTypeLoading = false;
      });
    },
    handleTransfer(row) {
      this.transferForm = {
        equipmentId: row.id,
        equipmentName: row.equipmentName,
        equipmentCode: row.equipmentCode,
        model: row.model,
        transferOutLocation: row.location,
        transferInLocation: '',
        reason: ''
      };
      this.transferDialogVisible = true;
    },
    submitTransfer() {
      this.$refs.transferFormRef.validate(valid => {
        if (!valid) return;
        // 这里调用接口保存调拨记录
        addTransferRecords(this.transferForm).then(() => {
          this.$message.success('调拨记录添加成功');
          this.transferDialogVisible = false;
          this.getList(); // 如需刷新设备列表
        });
      });
    },
    handleRepair(row) {
      // 初始化表单
      this.repairForm = {
        equipmentId: row.id,
        equipmentName: row.equipmentName,
        equipmentCode: row.equipmentCode,
        model: row.model,
        statusDescription: '',
        statusDescriptionAction: '',
        repairIssues: '',
        repairRecords: '',
        expectedCompletionTime: '',
        completionStatus: 2,
        isInfoChange: null,
        remark: '',
        // 其他字段
      };
      console.log(10, row);
      if (row.status == '5') { // 这里的"维修中"要和你的字典值一致
        // 获取维修记录列表
        newRepair(row.id).then(res => {
          console.log(11, res);
          const latest = res.data;
          if (latest) {
            // 只更新repairForm已有字段，且不添加多余字段
            Object.keys(this.repairForm).forEach(k => {
              if (Object.prototype.hasOwnProperty.call(latest, k)) {
                // 修复：isInfoChange强制转为字符串
                // if (k == 'isInfoChange' && latest[k] !== undefined && latest[k] !== null) {
                //   this.repairForm[k] = String(latest[k]);
                // } else {
                this.repairForm[k] = latest[k];
                // }
              }
            });
          }

          this.repairDialogVisible = true;
        });
      } else {
        this.repairDialogVisible = true;
      }
    },
    submitRepair() {
      this.$refs.repairFormRef.validate(valid => {
        if (!valid) return;
        console.log('维修记录添加', this.repairForm);
        addRepairHistory(this.repairForm).then(() => {
          this.$message.success('维修记录添加成功');
          this.repairDialogVisible = false;
          this.getList(); // 如需刷新设备列表
        });
      });
    },
    // 新增：显示维修记录日志弹框
    handleShowLogs(row) {
      this.logDialogVisible = true;
      this.logDetailInfo = {
        equipmentName: row.equipmentName,
        model: row.model,
        equipmentCode: row.equipmentCode,
        serialNumber: row.serialNumber,
        quantity: row.quantity,
        unit: row.unit,
        location: row.location,
        status: row.status,
      };
      this.logTimeline = [];
      // 并行获取维修记录和调拨记录
      Promise.all([
        listRepairHistory({ equipmentId: row.id }),
        listTransferRecords({ equipmentId: row.id })
      ]).then(([repairRes, transferRes]) => {
        // 维修记录，type: 'maintenance'
        const repairLogs = (repairRes.rows || []).map(item => ({
          date: this.changeTime(item.createTime),
          title: '设备维修',
          repairIssues: item.repairIssues, // 维修问题点
          repairRecords: item.repairRecords,// 维修记录
          completionStatus: item.completionStatus,// 维修完成状态
          // statusDescription: item.statusDescription, // 状态描述及处理,
          desc: item.statusDescription, // 状态描述
          isInfoChange: item.isInfoChange,
          type: 'maintenance',
        }));
        console.log(12, repairLogs);
        // 调拨记录，type: 'transfer'
        const transferLogs = (transferRes.rows || []).map(item => ({
          date: this.changeTime(item.createTime),
          title: '设备调拨',
          desc: item.remark,
          type: 'transfer',
          from: item.transferOutLocation,
          to: item.transferInLocation,
        }));
        // 合并并按时间降序排序
        this.logTimeline = [...repairLogs, ...transferLogs].sort((a, b) => new Date(b.date) - new Date(a.date));

      });
    },
    changeTime(time) {
      if (!time) return '';
      const date = new Date(time);
      if (isNaN(date.getTime())) return time;
      const pad = n => n < 10 ? '0' + n : n;
      const y = date.getFullYear();
      const m = pad(date.getMonth() + 1);
      const d = pad(date.getDate());
      const h = pad(date.getHours());
      const min = pad(date.getMinutes());
      const s = pad(date.getSeconds());
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
    },
    handleDetail(row) {
      getMain(row.id).then(response => {
        this.detailForm = response.data;
        this.detailDialogVisible = true;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
body {
  margin: 0;
  background: #f0f2f5;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

#app {
  padding: 20px;
}

.page-header {
  background: #fff;
  padding: 16px 32px;
  margin: -24px -24px 24px -24px;
  border-bottom: 1px solid #e8e8e8;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.stat-cards {
  margin-bottom: 24px;
}

.stat-card {
  position: relative;

  .el-card__body {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    min-height: 80px;
    padding-right: 60px;
  }

  .stat-icon {
    position: absolute;
    right: 16px;
    top: 16px;
    font-size: 48px;
    // opacity: 0.15;
    pointer-events: none;
    z-index: 1;
  }

  .stat-card-title {
    color: #606266;
    font-size: 14px;
    margin-bottom: 10px;
    font-weight: 500;
    z-index: 2;
  }

  .stat-card-num {
    font-size: 32px;
    font-weight: bold;
    z-index: 2;
    position: relative;
  }
}

.el-menu {
  border-right: none;
}

.app-container {
  height: calc(100vh - 140px); // 64px为顶部导航高度，按实际调整
  // max-height: calc(100vh - 140px); // 增加最大高度限制
  overflow: auto;
  box-sizing: border-box;
  padding-bottom: 24px; // 保证底部有空间
  // border: 1px solid red;
}

::v-deep .el-menu-item {
  position: relative;
}

.type-delete-icon {
  display: none;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.el-menu-item:hover .type-delete-icon {
  display: inline-block;
}

.device-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;

  .info-item {
    .label {
      font-size: 13px;
      color: #888;
      margin-bottom: 4px;
    }

    .value {
      font-size: 15px;
      color: #333;
      font-weight: 500;
      display: flex;
      align-items: center;

      .el-icon,
      i {
        margin-right: 4px;
      }
    }
  }
}

.timeline-card {
  .el-card__body {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .el-button {
    flex-shrink: 0;
    margin-left: 20px;
  }

  .timeline-title {
    font-weight: bold;
    color: #333;
  }

  .maintenance-desc {
    margin: 8px 0;
    font-size: 14px;
    color: #666;
    line-height: 1.8;

    .detail-label {
      color: #e74c3c;
      font-weight: bold;
    }
  }

  .transfer-desc,
  .default-desc {
    font-size: 14px;
    color: #666;
    line-height: 1.8;
    margin-top: 8px;
  }
}

.el-timeline {
  margin-top: 16px;
  padding-left: 8px;
}

.table-responsive {
  width: 100%;
  overflow-x: auto;
}

.el-table {
  min-width: 800px;
}

.no-wrap-row {
  flex-wrap: nowrap !important;
  overflow-x: auto;
}

.stat-col {
  min-width: 160px;
}

.compact-stat-card .el-card__body {
  min-height: 60px;
  padding-right: 40px;
  padding-top: 10px;
  padding-bottom: 10px;
}

.stat-card-title {
  font-size: 13px;
  margin-bottom: 6px;
}

.stat-card-num {
  font-size: 24px;
}

.stat-icon {
  font-size: 32px !important;
  top: 10px !important;
  right: 10px !important;
}

@media (max-width: 1200px) {
  .stat-card-num {
    font-size: 28px;
  }

  .stat-icon {
    font-size: 40px;
  }
}

@media (max-width: 992px) {
  .device-info {
    grid-template-columns: 1fr;
  }

  .el-col-sm-24 {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .stat-cards {
    .el-col-sm-24 {
      width: 50% !important;
      max-width: 50% !important;
      flex: 0 0 50% !important;
    }

    .stat-card {
      margin-bottom: 12px;
    }
  }

  .main-card {
    height: auto !important;
    min-height: 300px;
    overflow: visible;
  }

  .el-card {
    margin-bottom: 12px;
  }
}

@media (max-width: 600px) {
  .stat-cards {
    .el-col-sm-24 {
      width: 100% !important;
      max-width: 100% !important;
      flex: 0 0 100% !important;
    }
  }

  .app-container {
    padding: 4px;
  }

  .main-card {
    padding: 0 !important;
  }

  .el-table {
    min-width: 1000px;
  }
}

.ellipsis-cell {
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.daily-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.daily-detail-title {
  font-size: 28px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 36px;
  text-align: center;
  letter-spacing: 2px;
}

.daily-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 32px 0 16px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
  letter-spacing: 1px;
}

.daily-row-flex {
  display: flex;
  gap: 32px;
  margin-bottom: 12px;
}

.daily-col-flex {
  flex: 1;
}

.daily-detail-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: none;
}

.daily-detail-table th,
.daily-detail-table td {
  padding: 10px 8px;
  font-size: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.daily-detail-table th {
  width: 120px;
  color: #6b7a90;
  background: none;
  font-weight: normal;
  text-align: right;
  vertical-align: top;
  padding-right: 12px;
}

.daily-detail-table td.value {
  color: #222;
  text-align: left;
  font-weight: 500;
}

.daily-detail-table tr:last-child td,
.daily-detail-table tr:last-child th {
  border-bottom: none;
}

.daily-detail-table th.left-align {
  text-align: center;
  padding-left: 0;
  padding-right: 0;
  background: #f7fafd;
}

.daily-detail-table th.center-bg {
  text-align: center;
  vertical-align: middle;
  background: #f7fafd;
  width: 180px;
}

@media (max-width: 900px) {
  .daily-row-flex {
    flex-direction: column;
    gap: 0;
  }
}

.fixed-width-row {
  flex-wrap: wrap !important;
  overflow-x: visible;
  display: flex;
  gap: 20px 20px;
  /* 行间和列间间隙 */
}

.fixed-stat-col {
  width: 170px;
  min-width: 170px;
  max-width: 170px;
  flex: 0 0 170px;
  /* 去掉flex: 1 1 0; 保证宽度固定 */
  /* gap已由父容器控制间隙 */
}

.fixed-stat-col:last-child {
  margin-right: 0;
}
</style>
